package com.tms.control;

import com.tms.domain.Workcell;
import com.tms.service.WorkcellService;
import com.tms.utils.Data;
import com.tms.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static com.tms.core.constants.WorkcellConstants.*;

/**
 * 工作部门
 *
 * @author jackie
 * @date 2020.6.26
 */
@RestController
@RequestMapping("/api/workcells")
public class WorkcellController extends BaseController {

    @Autowired
    private WorkcellService workcellService;

    /**
     * 创建workcell
     * @param map 放在body里的workcell信息
     * @author jackie
     * @return 成功返回success，失败返回failed
     */
    @PostMapping
    public JsonResult newWorkcell(@RequestBody Map<String, String> map) {
        String name = map.get("name");
        //如果传过来的name为空
        if (name == null || name.length() == 0) {
            return new JsonResult(ERROR_NULL_NAME.getStatus(), ERROR_NULL_NAME.getDesc());
        }
        //数据库已存在该名字的workcell
        if (workcellService.findWorkcellByName(name) != null) {
            return new JsonResult(ERROR_EXIST_NAME.getStatus(), ERROR_EXIST_NAME.getDesc());
        }
        Workcell workcell = new Workcell(name);
        workcellService.createWorkcell(workcell);
        //判断是否创建成功，依据是插入成功会将分配的 id 值 set 到 workcell 的 id
        if (workcell.getId() == 0) {
            return new JsonResult(ERROR.getStatus(), ERROR.getDesc());
        }
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(workcell));
    }

    /**
     * 查询workcell
     *
     * @return 返回所有的workcell信息
     * @author jackie
     */
    @GetMapping
    public JsonResult viewWorkcell() {
        List<Workcell> workcells = workcellService.findAllWorkcells();
        if (workcells != null && !workcells.isEmpty()) {
            return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(workcells));
        }
        return new JsonResult(ERROR.getStatus(), ERROR.getDesc());
    }
}